
import re,sys
import string
from pepe.txt import bigtxt

#---------------------------------------------------------
def csv_creorder(inpFile, outFile, cOrder, cDelimiter):
    """ reorders csv file columns
    example: csv_creorder('IN.csv', 'OUT.csv', "5-18|13-38", "|") 
    """
    output = open(outFile,'w')
    cOrderTwins = string.split(cOrder,';')
    #print len(cOrderTwins)
    outColMax = int(max([ int(string.split(x,',')[0]) for x in cOrderTwins]))
    inpColMax = int(max([ int(string.split(x,',')[1]) for x in cOrderTwins]))
    # check out that input file has fields as requested in cOrder
    inpDelCnt = set([int(len(string.split(x, cDelimiter))) for x in bigtxt.lines(inpFile)])
    if len(inpDelCnt) == 1:
        for inpLine in bigtxt.lines(inpFile):
            inpLine = re.sub('\n','',inpLine)
            inpCols = string.split(inpLine, cDelimiter)
            outCols = ['']*(outColMax + 1)
            for cOrderTwin in cOrderTwins:
                x,y = string.split(cOrderTwin, ',')
                outCols[int(x)] = inpCols[int(y)]
            output.write(string.join([str(x) for x in outCols], cDelimiter)+'\n')
    else:
        print len(inpDelCnt),inpDelCnt
    output.close()
#---------------------------------------------------------
def csv_hshow(inpFile, cDelimiter):
    fLine = bigtxt.lines(inpFile)[0]
    iIndex = 0
    for col in string.split(fLine, cDelimiter):
        iIndex += 1
        print   string.rjust(inpFile,15), string.zfill(str(iIndex),3), col
#---------------------------------------------------------
def csv_vshow(inFile, cDelimiter, cIndex):
    iIndex = 0
    for line in bigtxt.lines(inFile):
        item = string.split(line, cDelimiter)[cIndex]
        iIndex += 1
        print string.rjust(inFile,15), string.zfill(str(iIndex),3), item,
#---------------------------------------------------------

def main():

    if len(sys.argv) == 4:
        #csv_hshow(sys.argv[1], '|')
        #csv_vshow('TEMPL.csv', '|', 0)
        csv_creorder(sys.argv[1], sys.argv[2], sys.argv[3], '|' )
    elif len(sys.argv) == 1:
        csv_hshow('outputAfterDelimCheck.csv', '|')
        csv_vshow('TEMPL.csv', '|', 0)
        csv_creorder('outputAfterDelimCheck.csv', 'OUT.csv', "3,7;4,6;7,5;9,4;14,10;18,11;19,13;21,12;29,14;37,8;40,9;49,0;50,1;51,16;52,17;53,3;54,2", "|")
    else:
        print csv_creorder.__doc__; os.system('pause')

if __name__ == "__main__":
    
    main()
